package com.motu.monstercity.server.game.logic;


import com.motu.monstercity.module.common.iap.IapGift;
import com.motu.monstercity.module.common.network.ResponseUtils;
import com.motu.monstercity.module.common.servermanager.ServerManager;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.protocol.CsGameSystem.CSGameSystemRedPointResponse;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.iap.GrowthFund;
import com.motu.monstercity.server.game.commondata.iap.PrivilegeCard;
import com.motu.monstercity.server.game.commondata.iap.PrivilegeCardConstant;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class IapManager extends IapUserData {

    // 初始化下发充值付费模块的用户数据
    public static void loadInitIapUserData(Common.PBUserData.Builder pbUserData, UserInfo userInfo) {
        long userId = userInfo.getId();
        //特权卡数据
        List<UserPrivilegeCard> userPrivilegeCardList = IapManager.getUserPrivilegeCardList(userId);
        for (UserPrivilegeCard userPrivilegeCard : userPrivilegeCardList) {
            ProtoDataUtils.updatePBUserData(pbUserData, userPrivilegeCard, true);
        }

        long curTime = TimeUtils.getCurTime();
        List<UserIapGiftPush> userIapGiftPushList = GameUser.getUserIapGiftPushList(userId);
        for (UserIapGiftPush userIapGiftPush : userIapGiftPushList) {
            IapGift iapGift = IapManager.getIapGift(userIapGiftPush.getIapGiftId());
            if (iapGift == null) {
                continue;
            }
            if (userIapGiftPush.getEndTime() < curTime) {
                continue;
            }
            ProtoDataUtils.updatePBUserData(pbUserData, userIapGiftPush, true);
        }
    }

    // 获取特权卡对应的数值
    public static int takePrivilegeValueByType(long userId, String type) {
        int value = 0;
        List<UserPrivilegeCard> userPrivilegeCardList = IapManager.getUserPrivilegeCardList(userId);
        for (UserPrivilegeCard userPrivilegeCard : userPrivilegeCardList) {
            int privilegeType = userPrivilegeCard.getType();
            if (!userPrivilegeCard.isExpired()) {
                PrivilegeCard privilegeCard = IapManager.getPrivilegeCard(privilegeType);
                switch (type) {
                    case PrivilegeCardConstant.TYPE_CHILD_NUM:
                        //城市收益增加 (百分比)
                        value += privilegeCard.getChildNum();
                        break;
                    case PrivilegeCardConstant.TYPE_EARN_NUM:
                        //教学体力上限增加
                        value += privilegeCard.getEarnNum();
                        break;
                    case PrivilegeCardConstant.TYPE_GOLD_NUM:
                        //每日可多领取num（小时）金币
                        value += privilegeCard.getGoldNum();
                        break;
                    case PrivilegeCardConstant.TYPE_STAGE_NUM:
                        // 关卡损耗率减少 (百分比)
                        value += privilegeCard.getStageNum();
                        break;
                    case PrivilegeCardConstant.TYPE_OFF_TIME_ADD_NUM:
                        // 增加的离线收益时间上限单位(单位小时)
                        value += privilegeCard.getOffTimeAdd();
                        break;
                    case PrivilegeCardConstant.TYPE_IS_GUILD_BUILD_1:
                        // 公会中级建设是否免费 (0:否 1:是)
                        value += privilegeCard.getIsGuildBuild1();// >0:代表是  == 0 代表否
                        break;
                    case PrivilegeCardConstant.TYPE_IS_GUILD_BUILD_2:
                        // 公会高级建设是否免费 (0:否 1:是)
                        value += privilegeCard.getIsGuildBuild2();// >0:代表是  == 0 代表否
                        break;
                    case PrivilegeCardConstant.TYPE_IS_SNATCH:
                        // 贸易站储存是否无上限 (0:否 1:是)
                        value += privilegeCard.getIsSnatch();// >0:代表是  == 0 代表否
                        break;
                    case PrivilegeCardConstant.TYPE_HOSPITAL_RECOVER_VALUE:
                        // 医院每秒恢复伤员的数量加成
                        value += privilegeCard.getHospitalRecoverValue();
                        break;
                    case PrivilegeCardConstant.TYPE_GUARD_TIME_ADD:
                        //  围墙挂机时间上限增加(单位分钟)
                        value += privilegeCard.getGuardTimeAdd();
                        break;
                    case PrivilegeCardConstant.TYPE_GUARD_QUICK_NUM:
                        // 围墙挂机额外领取次数增加
                        value += privilegeCard.getGuardQuickNum();
                        break;
                    case PrivilegeCardConstant.TYPE_SKIN_AD:// 是否跳过广告
                        value += privilegeCard.getAd();
                        break;
                    case PrivilegeCardConstant.TYPE_UNION_HELP_NUM:// 被联盟成员互助的人数上限增加
                        value += privilegeCard.getUnionBehelpNum();
                        break;
                    default:
                        break;
                }

            }
        }
        return value;
    }

    public static boolean checkRedPoint(UserInfo userInfo, CsGameSystem.CSGameSystemRedPointResponse.Builder red_build) {
        boolean hasRedPoint = false;
        CsGameSystem.RedPoint_Iap.Builder redPoint = CsGameSystem.RedPoint_Iap.newBuilder();
        long userId = userInfo.getId();
        //基金红点
        List<UserGrowthFund> userGrowthFundList = new ArrayList<>();
        UserGrowthFund userGrowthFund113 = IapManager.getUserGrowthFund(userId,MainTaskConstant.TASK_TYPE_113);
        if (userGrowthFund113 == null) {
            userGrowthFund113 = new UserGrowthFund(userId, MainTaskConstant.TASK_TYPE_113);
        }
        userGrowthFundList.add(userGrowthFund113);
        UserGrowthFund userGrowthFund144 = IapManager.getUserGrowthFund(userId,MainTaskConstant.TASK_TYPE_144);
        if (userGrowthFund144 == null) {
            userGrowthFund144 = new UserGrowthFund(userId, MainTaskConstant.TASK_TYPE_144);
        }
        userGrowthFundList.add(userGrowthFund144);
        UserGrowthFund userGrowthFund184 = IapManager.getUserGrowthFund(userId,MainTaskConstant.TASK_TYPE_184);
        if (userGrowthFund184 == null) {
            userGrowthFund184 = new UserGrowthFund(userId, MainTaskConstant.TASK_TYPE_184);
        }
        userGrowthFundList.add(userGrowthFund184);
        UserGrowthFund userGrowthFund141 = IapManager.getUserGrowthFund(userId,MainTaskConstant.TASK_TYPE_141);
        if (userGrowthFund141 == null) {
            userGrowthFund141 = new UserGrowthFund(userId, MainTaskConstant.TASK_TYPE_141);
        }
        userGrowthFundList.add(userGrowthFund141);
        UserGrowthFund userGrowthFund117 = IapManager.getUserGrowthFund(userId,MainTaskConstant.TASK_TYPE_117);
        if (userGrowthFund117 == null) {
            userGrowthFund117 = new UserGrowthFund(userId, MainTaskConstant.TASK_TYPE_117);
        }
        userGrowthFundList.add(userGrowthFund117);
        for(UserGrowthFund userGrowthFund : userGrowthFundList){
            int[] GROWTH_FUND = userGrowthFund.getGrowthFund();
            int type = userGrowthFund.getType();
            ConcurrentHashMap<Long, GrowthFund> growthFundGroupMap = null;
            for (int groupId = 1; groupId <= GROWTH_FUND.length; groupId++) {
                growthFundGroupMap = IapManager.getGrowthFundGroupMap(type,groupId);
                if (growthFundGroupMap == null) {
                    break;
                }
                JsonArray freeRewardAry = userGrowthFund.getFreeRewardAry(groupId);
                JsonArray payRewardAry = userGrowthFund.getPayRewardAry(groupId);
                List<GrowthFund> freeList = new ArrayList<>();//可领免费奖励
                List<GrowthFund> payList = new ArrayList<>();//可领付费奖励
                long achieveNum = MainTaskManager.takeGrowthProgress(userInfo,type);

                for (GrowthFund growthFund : growthFundGroupMap.values()) {
                    // 不满足领奖条件
                    if (achieveNum < growthFund.getNum()) {
                        continue;
                    }
                    if (!Tool.isInList(freeRewardAry,growthFund.getNum())) {
                        freeList.add(growthFund);
                    }
                    if (userGrowthFund.isBuy(groupId) && !Tool.isInList(payRewardAry,growthFund.getNum())) {
                        payList.add(growthFund);
                    }
                }
                if (freeList.size() >0 || payList.size() > 0 ) {
                    redPoint.setFund(true);
                    hasRedPoint = true;
                    break;
                }
            }
        }

        //免费礼包是否可领取
        List<IapGift>  dayGiftList = IapManager.getIapGiftTypeList(IapGift.TYPE_DAY);//每日礼包
        for(IapGift iapGift : dayGiftList){
            if (iapGift.getIapId() == 0 ){
                //免费礼包
                UserIapGift userIapGift = IapManager.getUserIapGift(userId,iapGift.getId());
                if(userIapGift == null || userIapGift.getNum() == 0) {
                    redPoint.setFreeDayGift(true);
                    hasRedPoint = true;
                }
            }
        }
        List<IapGift>  weekGiftList = IapManager.getIapGiftTypeList(IapGift.TYPE_WEEK);//每周礼包
        for(IapGift iapGift : weekGiftList){
            if (iapGift.getIapId() == 0 ){
                //免费礼包
                UserIapGift userIapGift = IapManager.getUserIapGift(userId,iapGift.getId());
                if(userIapGift == null || userIapGift.getNum() == 0) {
                    redPoint.setFreeWeekGift(true);
                    hasRedPoint = true;
                }
            }
        }
        List<IapGift>  monthGiftList = IapManager.getIapGiftTypeList(IapGift.TYPE_MONTH);//每月礼包
        for(IapGift iapGift : monthGiftList){
            if (iapGift.getIapId() == 0 ){
                //免费礼包
                UserIapGift userIapGift = IapManager.getUserIapGift(userId,iapGift.getId());
                if(userIapGift == null || userIapGift.getNum() == 0) {
                    redPoint.setFreeMonthGift(true);
                    hasRedPoint = true;
                }
            }
        }
        // 广告礼包红点
        int count = 0;
        UserAdvideo userAdvideo = GameUser.getUserAdvideo(userId);
        for (int actType: IapGift.AD_GIFTS){
            List<IapGift>  giftList =  IapManager.getIapGiftTypeList(actType);
            for(IapGift iapGift : giftList){
                if (iapGift.getIapId() != AdvideoManager.ADVIDEO_CODE){
                    continue;
                }
                int dayNum = userAdvideo.takeDayNum(AdvideoManager.ADVIDEO_TYPE_1, iapGift.getId());
                if (actType == IapGift.TYPE_BENEFIT_AD_GIFT){  // 每日放映礼包
                    if (dayNum <= 0) continue; // 没有数据的过滤掉
                    if (dayNum < iapGift.getLimitNum()){
                        redPoint.putAdGift( IapGift.TYPE_BENEFIT_AD_GIFT, 1);  // 类型-> 红点
                        break;
                    } else if ( dayNum >= iapGift.getLimitNum()) {
                       count++;
                    }
                }else{
                    if (dayNum < iapGift.getLimitNum()) {
                        redPoint.putAdGift(actType,1);  // 类型-> 红点
                        hasRedPoint = true;
                        break;
                    }
                }
            }
        }
        if (count < AllParam.BENEFIT_AD_AIP_AD_NUM){
            redPoint.putAdGift(IapGift.TYPE_BENEFIT_AD_GIFT, 1);  // 类型-> 红点
        }
        // 系统广告红点
        for (int systemId: SystemConstant.AD_GIFTS){
            if (!SystemManager.checkModuleOpen(userInfo, systemId)) continue;  // 系统是否解锁
            boolean isTurnOn = false;
            if (isTurnOn){
                redPoint.putSysAdGift(systemId,1);  // 类型-> 红点
                hasRedPoint = true;
            }
        }
        red_build.setIap(redPoint);
        return hasRedPoint;
    }

    /**
     * 领取特权卡奖励
     * @param pbUserData
     * @param userInfo
     */
    public static void getPrivilegeCardReward(PBUserData.Builder pbUserData, UserInfo userInfo, UserPower userPower, UserPrivilegeCard userPrivilegeCard) {
        if (userPrivilegeCard == null) {
            return;
        }
        if (userPrivilegeCard.isExpired() || TimeUtils.isToday(userPrivilegeCard.getDailyRewardTime())) {
            return;// 已经过期。或是今天已经领取过了
        }

        PrivilegeCard privilegeCard = IapManager.getPrivilegeCard(userPrivilegeCard.getType());
        if (privilegeCard == null) {
            return;
        }

        // 领取奖励
        if (privilegeCard.getGoldNum() > 0) {// 每日可多领取num（小时）金币
            long earn = userPower.getEarn();// 玩家的城市收益,每秒
            long goldNum = earn * privilegeCard.getGoldNum() *  TimeUtils.HOUR;
            RewardManager.addReward(userInfo, ItemId.GOLD, goldNum, pbUserData, LogType.PRIVILEGE_REWARD_DAILY, userPrivilegeCard.getType());
        }
        if (privilegeCard.getDiamondNum() > 0) {
            RewardManager.addReward(userInfo, ItemId.DIAMOND, privilegeCard.getDiamondNum(), pbUserData, LogType.PRIVILEGE_REWARD_DAILY, userPrivilegeCard.getType());
        }
        if (!Tool.isEmpty(privilegeCard.getDailyReward())) {
            RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(privilegeCard.getDailyReward()), pbUserData, LogType.PRIVILEGE_REWARD_DAILY, userPrivilegeCard.getType());
        }


        // 更新领取时间
        userPrivilegeCard.putDailyRewardTime(TimeUtils.getCurTime());
        userPrivilegeCard.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userPrivilegeCard);
    }

    /**
     * 基金奖励有新的可领取时。给玩家推送红点
     * @param userInfo
     * @param type 113-城市基金，144-专员基金，184-收益基金，141-英雄基金，117-后代基金
     * @param achieveNum  最新的任务进度值
     */
    public static void sendGrowFundRedPoint(UserInfo userInfo, int type, long achieveNum) {
        if (checkGrowFundRedPoint(userInfo, type, achieveNum)) {
            CSGameSystemRedPointResponse.Builder builder = CSGameSystemRedPointResponse.newBuilder();
            CsGameSystem.RedPoint_Iap.Builder redPointIap = CsGameSystem.RedPoint_Iap.newBuilder();
            redPointIap.setFund(true);

            builder.setIap(redPointIap);
            builder.setPromptType(SystemConstant.RED_POINT_IAP_GROW_FUND);
            JsonObject jsonObject = ResponseUtils.getRedpointResponseData( builder.build().toByteArray());
            GameUser.pushToUser(userInfo.getId(), jsonObject);
        }
    }


    /**
     * 判断是否有可领取的基金
     * @param userInfo
     * @param type 113-城市基金，144-专员基金，184-收益基金，141-英雄基金，117-后代基金
     * @param achieveNum
     * @return
     */
    private static boolean checkGrowFundRedPoint(UserInfo userInfo, int type, long achieveNum) {
        long userId = userInfo.getId();
        UserGrowthFund userGrowthFund = IapManager.getUserGrowthFund(userId, type);
        if (userGrowthFund == null) {
            userGrowthFund = new UserGrowthFund(userId, type);
        }
        int[] GROWTH_FUND = userGrowthFund.getGrowthFund();
        ConcurrentHashMap<Long, GrowthFund> growthFundGroupMap = null;
        for (int groupId = 1; groupId <= GROWTH_FUND.length; groupId++) {
            growthFundGroupMap = IapManager.getGrowthFundGroupMap(type,groupId);
            if (growthFundGroupMap == null) {
                return  false;
            }
            JsonArray freeRewardAry = userGrowthFund.getFreeRewardAry(groupId);
            JsonArray payRewardAry = userGrowthFund.getPayRewardAry(groupId);
            List<GrowthFund> freeList = new ArrayList<>();//可领免费奖励
            List<GrowthFund> payList = new ArrayList<>();//可领付费奖励
            for (GrowthFund growthFund : growthFundGroupMap.values()) {
                // 不满足领奖条件
                if (achieveNum < growthFund.getNum()) {
                    continue;
                }
                if (!Tool.isInList(freeRewardAry,growthFund.getNum())) {
                    freeList.add(growthFund);
                }
                if (userGrowthFund.isBuy(groupId) && !Tool.isInList(payRewardAry,growthFund.getNum())) {
                    payList.add(growthFund);
                }
            }
            if (freeList.size() >0 || payList.size() > 0 ) {
                return true;
            }
        }
        return false;
    }
}
